﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MockPrjTeam2.Biz;
using MockPrjTeam2.Entity;
using MockPrjTeam2.Pages.ControlOrg;
using System.Data;

namespace MockPrjTeam2.Pages.Forms
{
    public partial class OrganizationDetails : System.Web.UI.Page
    {
        int organizationId;
        private OrganizationBuz bus;
        protected void Page_Load(object sender, EventArgs e)
        {
            string script =
                @"<script>
                          function OpenPopupBussiness() {
                            popup('../Views/PopupSearchBussiness.aspx');
                        }
                             function OpenPopup() {
                            popup('PopupListContacts.aspx');
                        }
                          function OpenPopupAddress() {
                            popup('../Views/PopupSearchAddress.aspx');
                        }
                        function popup(url) {
            
                            var width = 500;
                            var height = 400;
                            var left = (screen.width - width) / 2;
                            var top = (screen.height - height) / 2;
                            var params = 'width=' + width + ', height=' + height;
                            params += ', top=' + top + ', left=' + left;
                            params += ', directories=no';
                            params += ', location=no';
                            params += ', menubar=no';
                            params += ', resizable=no';
                            params += ', scrollbars=no';
                            params += ', status=no';
                            params += ', toolbar=no';
                            newwin = window.open(url, 'windowname5', params);
                            if (window.focus) { newwin.focus() }
                            return false;
                        }
                        </script>";
            if (!Page.ClientScript.IsStartupScriptRegistered("Mast"))
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(),
                                                        "Mast", script);
            }



            if (!int.TryParse(Request.Params["id"], out organizationId))
            {
                Response.Redirect("../Views/ListOrganizations.aspx");
            }
            else
            {
                bus = new OrganizationBuz();

            }
            if (!IsPostBack)
            {
                GetOrganizationById();
              
            }
            LoadDirectorateFrame();
            LoadSupportingMaterialFrame();
           
        }


        private void GetCountry(int countryId)
        {

            var countryBiz = new CountryBiz();
            DropDownListNationCounty.DataSource = countryBiz.GetAllCountry();
            DropDownListNationCounty.DataTextField = "CountryName";
            DropDownListNationCounty.DataValueField = "CountryID";
            DropDownListNationCounty.DataBind();
            DropDownListNationCounty.SelectedValue = countryId.ToString(CultureInfo.InvariantCulture);
        }
        private void GetOrganizationById()
        {
            
            Organization org = bus.GetOrganizationById(organizationId);

            TextBoxOrganizationName.Text = org.OrganizationName;
            TextBoxShortDescription.Text = org.ShortDescription;
            txtContact.Text = org.ContactName;
            TextBoxAddressLine1.Text = org.AddressLine1;
            TextBoxAddressLine2.Text = org.AddressLine2;
            TextBoxAddressLine3.Text = org.AddressLine3;
            txtPostCode.Text = org.PostCode;
            TextBoxCityTown.Text = org.CityTown;
            TextBoxCounty.Text = org.County;
            txtBussinessName.Text = org.BussinessType;
            TxtSicCode.Text = org.SicCode;
            TextBoxFullDescription.Text = org.FullDescription;
            TextBoxPhoneNumber.Text = org.PhoneNumber;
            TextBoxFax.Text = org.Fax;
            TextBoxEmail.Text = org.Email;
            TextBoxWebAddress.Text = org.WebAddress;
            TextBoxCharityNumber.Text = org.CharityNumber;
            TextBoxCompanyNumber.Text = org.CompanyNumber;
            hdnContactId.Value = org.ContactId.ToString();
            hdnAddressId.Value = org.AddressId.ToString();
            hdnBussId.Value = org.BusinessTypeId.ToString();
            HiddenFieldOrganizationId.Value = org.OrganizationId.ToString();
            hdnOrganizationName.Value = org.OrganizationName;
            if (org.PreferredOrganization)
            {
                CheckBoxPreferredOrganization.Checked = true;
            }

            string[] orgSpecial = org.OrganizationSpecialism.Split(';');
            string[] serviceDisablities = org.ServiceDisabilities.Split(';');
            string[] serviceBarriers = org.ServiceBarriers.Split(';');
            string[] serviceBenefits = org.ServiceBenefits.Split(';');
            string[] serviceCircumstancesS = org.ServiceCircumstances.Split(';');
            string[] serviceEnthnicity = org.ServiceEthnicity.Split(';');
            string[] accreditation = org.Accreditation.Split(';');


           
            foreach (string s in orgSpecial)
            {
                if (CheckBoxListOrgSpecial.Items.FindByText(s) != null)
                {
                    CheckBoxListOrgSpecial.Items.FindByText(s).Selected = true;
                }
            }

            foreach (string s1 in serviceDisablities)
            {
                if (CheckBoxListDisabilities.Items.FindByText(s1) != null)
                {
                    CheckBoxListDisabilities.Items.FindByText(s1).Selected = true;
                }
            }
            foreach (string s2 in serviceBarriers)
            {
                if (CheckBoxListBarriers.Items.FindByText(s2) != null)
                {
                    CheckBoxListBarriers.Items.FindByText(s2).Selected = true;
                }
            }
            foreach (string s3 in serviceBenefits)
            {
                if (CheckBoxListBenefits.Items.FindByText(s3) != null)
                {
                    CheckBoxListBenefits.Items.FindByText(s3).Selected = true;
                }
            }
            foreach (string s4 in serviceCircumstancesS)
            {
                if (CheckBoxListCircumstances.Items.FindByText(s4) != null)
                {
                    CheckBoxListCircumstances.Items.FindByText(s4).Selected = true;
                }
            }
            foreach (string s5 in serviceEnthnicity)
            {
                if (CheckBoxListEthnicity.Items.FindByText(s5) != null)
                {
                    CheckBoxListEthnicity.Items.FindByText(s5).Selected = true;
                }
            }
            foreach (string s6 in accreditation)
            {
                if (CheckBoxListAccreditation.Items.FindByText(s6) != null)
                {
                    CheckBoxListAccreditation.Items.FindByText(s6).Selected = true;
                }
            }
            this.GetCountry(org.CountryId);
        }

        public int CheckOrganizationNameExist(string orgName)
        {
            OrganizationBuz organizationBuz = new OrganizationBuz();
            return organizationBuz.CheckOrganizationNameExist(orgName);
        }
        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            OrganizationBuz bus = new OrganizationBuz();
            Organization organization = new Organization();
            organization.OrganizationId = organizationId;
            int checkOrganizationName = CheckOrganizationNameExist(TextBoxOrganizationName.Text);
            if (organization.OrganizationName != null && (!organization.OrganizationName.Equals(hdnOrganizationName.Value)&&checkOrganizationName > 0))
            {
                

                return;
            }
            organization.OrganizationName = TextBoxOrganizationName.Text;
            organization.ShortDescription = TextBoxShortDescription.Text;
            organization.ContactId = Int32.Parse(hdnContactId.Value);
            organization.AddressLine1 = TextBoxAddressLine1.Text;
            organization.AddressLine2 = TextBoxAddressLine2.Text;
            organization.AddressLine3 = TextBoxAddressLine3.Text;
            organization.AddressId = Int32.Parse(hdnAddressId.Value);
            organization.CityTown = TextBoxCityTown.Text;
            organization.County = TextBoxCounty.Text;
            organization.CountryId = Convert.ToInt32(DropDownListNationCounty.SelectedValue);
            organization.BusinessTypeId = Int32.Parse(hdnBussId.Value);

            organization.FullDescription = TextBoxFullDescription.Text;
            organization.PhoneNumber = TextBoxPhoneNumber.Text;
            organization.Fax = TextBoxFax.Text;
            organization.Email = TextBoxEmail.Text;
            organization.WebAddress = TextBoxWebAddress.Text;
            organization.CharityNumber = TextBoxCharityNumber.Text;
            organization.CompanyNumber = TextBoxCompanyNumber.Text;

            //
            string organizationSpecialism = string.Empty;
            string serviceDisablities = string.Empty;
            string serviceBarriers = string.Empty;
            string serviceBenefits = string.Empty;
            string serviceCircumstancesS = string.Empty;
            string serviceEnthnicity = string.Empty;
            string accreditation = string.Empty;

            foreach (ListItem item in CheckBoxListOrgSpecial.Items)
            {
                if (item.Selected)
                {
                    organizationSpecialism += item.Value + ";";
                }
            }
            foreach (ListItem item in CheckBoxListDisabilities.Items)
            {
                if (item.Selected)
                {
                    serviceDisablities += item.Value + ";";
                }
            }
            foreach (ListItem item in CheckBoxListBarriers.Items)
            {
                if (item.Selected)
                {
                    serviceBarriers += item.Value + ";";
                }
            }
            foreach (ListItem item in CheckBoxListBenefits.Items)
            {
                if (item.Selected)
                {
                    serviceBenefits += item.Value + ";";
                }
            }
            foreach (ListItem item in CheckBoxListCircumstances.Items)
            {
                if (item.Selected)
                {
                    serviceCircumstancesS += item.Value + ";";
                }
            }
            foreach (ListItem item in CheckBoxListEthnicity.Items)
            {
                if (item.Selected)
                {
                    serviceEnthnicity += item.Value + ";";
                }
            }

            foreach (ListItem item in CheckBoxListAccreditation.Items)
            {
                if (item.Selected)
                {
                    accreditation += item.Value + ";";
                }
            }
            organization.ServiceDisabilities = serviceDisablities;
            organization.OrganizationSpecialism = organizationSpecialism;

            organization.ServiceBarriers = serviceBarriers;
            organization.ServiceBenefits = serviceBenefits;
            organization.ServiceCircumstances = serviceCircumstancesS;
            organization.ServiceEthnicity = serviceEnthnicity;
            organization.Accreditation = accreditation;
            var programmeIds = new List<int>();
            var serviceIds = new List<int>();
            foreach (ListItem item in CblPrograms.Items)
            {

                if (item.Selected)
                {

                    programmeIds.Add(Convert.ToInt32(item.Value));

                }
            }
          
            foreach (ListItem item in CblServices.Items)
            {
                if (item.Selected)
                {

                  serviceIds.Add(Convert.ToInt32(item.Value));

                }
            }
            OrganizationService organizationService=new OrganizationService();
            int orgId =Convert.ToInt32(HiddenFieldOrganizationId.Value);
            bool result = bus.UpdateOrganization(organization);
            //organizationService.OrganizationId = orgId;
           // organizationService.ServiceId =List<serviceIds>;
            bool result1 = bus.UpdateOrganizationPro(orgId, programmeIds);
            bool result2 = bus.UpdateOrganizationServ(orgId, serviceIds);
            if (result&&result1&&result2)
            {
                
                    Response.Redirect("../Views/ListOrganizations.aspx");
                
            }
            else
            {
                 lblCheckOrgName.Text = "OrganizationName does exist ! Please new OrganizationName !";
            }
        }
        private void LoadDirectorateFrame()
        {

            DetailsPanel06.Visible = true;
            LinkDetails06.Visible = true;

            var directorateFrame =
                (DirectorateListFrame)Page.LoadControl("~/Pages/ControlOrg/DirectorateListFrame.ascx");

            HolderDirectorate.Controls.Clear();
            HolderDirectorate.Controls.Add(directorateFrame);
        }
        private void LoadSupportingMaterialFrame()
        {
            SupportingMeterialBiz supportingMeterialBiz = new SupportingMeterialBiz();
            int organisationId = Convert.ToInt32(HiddenFieldOrganizationId.Value);

            DetailsPanel05.Visible = true;
            LinkDetails05.Visible = true;
            var supportingMaterialListFrame =
                (SupportingMeterialListFrame)
                Page.LoadControl("~/Pages/ControlOrg/SupportingMeterialListFrame.ascx");
            supportingMaterialListFrame.orgId = organisationId;
            HolderSupportingMaterial.Controls.Clear();
            HolderSupportingMaterial.Controls.Add(supportingMaterialListFrame);

        }

        protected void ButtonInactive_Command(object sender, CommandEventArgs e)
        {
            int organisationId;
            if (int.TryParse(HiddenFieldOrganizationId.Value, out organisationId))
            {
                OrganizationBuz organizationBuz=new OrganizationBuz();
                organizationBuz.SetOrganizationInActive(organisationId, false);
                ButtonInactive.Visible = false;
            }
        }

        protected void CheckBoxInterest_CheckedChanged(object sender, EventArgs e)
        {
            LinkDetails03.Visible = CheckBoxInterest.Checked;
            DetailsPanel03.Visible = CheckBoxInterest.Checked;
            GetService();
            GetProgramme();
            var dtService = new DataTable();
            var dtProgramme = new DataTable();
            dtService = bus.GetOrganizationServiceByOrgId(organizationId);
            dtProgramme = bus.GetOrganizationProgrammeByOrgId(organizationId);
            foreach (DataRow itemProgramme in dtProgramme.Rows)
            {
                var programSelected = itemProgramme["ProgrammeID"].ToString();
                if(CblPrograms.Items.FindByValue(programSelected)!=null)
                {
                    CblPrograms.Items.FindByValue(programSelected).Selected = true;
                }
            }
            foreach (DataRow itemService in dtService.Rows)
            {
                var serviceSelected = itemService["ServiceID"].ToString();
                if (CblServices.Items.FindByValue(serviceSelected) != null)
                {
                    CblServices.Items.FindByValue(serviceSelected).Selected = true;
                }
            }
        }

        private void GetService()
        {

            ServiceBiz serviceBiz = new ServiceBiz();
            CblServices.DataSource = serviceBiz.GetAll();
            CblServices.DataTextField = "ServiceName";
            CblServices.DataValueField = "ServiceID";

            CblServices.DataBind();

        }
        private void GetProgramme()
        {
            ProgrammeBiz programmeBiz = new ProgrammeBiz();
            CblPrograms.DataSource = programmeBiz.GetallProgramme();
            CblPrograms.DataTextField = "ProgrammeName";
            CblPrograms.DataValueField = "ProgrammeID";

            CblPrograms.DataBind();
        }

      


    }
}
